package cn.cicoding.service.impl;

import cn.cicoding.dao.UserRepository;
import cn.cicoding.entity.User;
import cn.cicoding.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public User findById(String userId) {
        return userRepository.findById(userId).orElse(new User());
    }

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteById(String userId) {
        User user = new User();
        user.setUserId(userId);
        userRepository.deleteById(userId);
    }

    /**
     * 只分页,无查询条件
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<User> findAllUsers(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        return userRepository.findAll(pageRequest);
    }

    /**
     * 根据所有的参数条件查询分页
     *
     * @param page
     * @param size
     * @param user
     * @return
     */
    @Override
    public Page<User> findAllUsersByUser(int page, int size, User user) {
        Sort sort = Sort.by(Sort.Direction.DESC, "age");
        //0为第一页
        Pageable pageable = PageRequest.of(0, 10, sort);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        user.setName("四");
        //创建实例
        Example<User> example = Example.of(user, matcher);
        Page<User> pages = userRepository.findAll(example, pageable);
        System.out.println(pages);
        return pages;
    }
}
